package cn.chiship.sdk.core.util.ip;

import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.exception.custom.SystemErrorException;
import cn.chiship.sdk.core.util.PlatformUtil;
import cn.chiship.sdk.core.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.*;
import java.util.Enumeration;

/**
 * 获取IP方法
 *
 * @author lijian
 */
public class IpUtils {

	private static final Logger log = LoggerFactory.getLogger(IpUtils.class);

	private static final int TWO = 2;

	private static final int FOUR = 4;

	/**
	 * 获取ip工具类，除了getRemoteAddr，其他ip均可伪造
	 * @param request
	 * @return 结果
	 */
	public static String getIpAddr(HttpServletRequest request) {

		/**
		 * 网宿cdn的真实ip
		 */
		String ip = request.getHeader("Cdn-Src-Ip");
		if (ip == null || ip.length() == 0 || BaseConstants.STRING_UNKNOWN.equalsIgnoreCase(ip)) {
			/**
			 * 蓝讯cdn的真实ip
			 */
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || BaseConstants.STRING_UNKNOWN.equalsIgnoreCase(ip)) {
			/**
			 * 获取代理ip
			 */
			ip = request.getHeader("X-Forwarded-For");
		}
		if (ip == null || ip.length() == 0 || BaseConstants.STRING_UNKNOWN.equalsIgnoreCase(ip)) {
			/**
			 * 获取代理ip
			 */
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || BaseConstants.STRING_UNKNOWN.equalsIgnoreCase(ip)) {
			/**
			 * 获取代理ip
			 */
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || BaseConstants.STRING_UNKNOWN.equalsIgnoreCase(ip)) {
			/**
			 * 获取真实ip
			 */
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 过滤出真实IP Example 144.123.183.66, 39.104.55.144
	 * @param ip
	 * @return 结果
	 */
	public static String filterIp(String ip) {
		if (!StringUtil.isNullOrEmpty(ip)) {
			return ip.split(", ")[0];
		}
		return ip;
	}

	public static boolean internalIp(String ip) {
		byte[] addr = textToNumericFormatV4(ip);
		return internalIp(addr) || "127.0.0.1".equals(ip);
	}

	private static boolean internalIp(byte[] addr) {
		if (StringUtil.isNull(addr) || addr.length < TWO) {
			return true;
		}
		final byte b0 = addr[0];
		final byte b1 = addr[1];
		// 10.x.x.x/8
		final byte SECTION_1 = 0x0A;
		// 172.16.x.x/12
		final byte SECTION_2 = (byte) 0xAC;
		final byte SECTION_3 = (byte) 0x10;
		final byte SECTION_4 = (byte) 0x1F;
		// 192.168.x.x/16
		final byte SECTION_5 = (byte) 0xC0;
		final byte SECTION_6 = (byte) 0xA8;
		switch (b0) {
		case SECTION_1:
			return true;
		case SECTION_2:
			if (b1 >= SECTION_3 && b1 <= SECTION_4) {
				return true;
			}
		case SECTION_5:
			return b1 == SECTION_6;
		default:
			return false;
		}
	}

	/**
	 * 将IPv4地址转换成字节
	 * @param text IPv4地址
	 * @return 结果 byte 字节
	 */
	public static byte[] textToNumericFormatV4(String text) {
		byte[] empty = new byte[0];
		if (text.length() == 0) {
			return empty;
		}

		byte[] bytes = new byte[4];
		String[] elements = text.split("\\.", -1);
		try {
			long aa = 4294967295L;
			long bb = 255L;
			long cc = 16777215L;
			long dd = 65535L;
			long l;
			int i;
			switch (elements.length) {
			case 1:
				l = Long.parseLong(elements[0]);
				if ((l < 0L) || (l > aa)) {
					return empty;
				}
				bytes[0] = (byte) (int) (l >> 24 & 0xFF);
				bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
				bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
				bytes[3] = (byte) (int) (l & 0xFF);
				break;
			case 2:
				l = Integer.parseInt(elements[0]);
				if ((l < 0L) || (l > bb)) {
					return empty;
				}
				bytes[0] = (byte) (int) (l & 0xFF);
				l = Integer.parseInt(elements[1]);
				if ((l < 0L) || (l > cc)) {
					return empty;
				}
				bytes[1] = (byte) (int) (l >> 16 & 0xFF);
				bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
				bytes[3] = (byte) (int) (l & 0xFF);
				break;
			case 3:
				for (i = 0; i < TWO; ++i) {
					l = Integer.parseInt(elements[i]);
					if ((l < 0L) || (l > 255L)) {
						return empty;
					}
					bytes[i] = (byte) (int) (l & 0xFF);
				}
				l = Integer.parseInt(elements[2]);
				if ((l < 0L) || (l > dd)) {
					return empty;
				}
				bytes[2] = (byte) (int) (l >> 8 & 0xFF);
				bytes[3] = (byte) (int) (l & 0xFF);
				break;
			case 4:
				for (i = 0; i < FOUR; ++i) {
					l = Integer.parseInt(elements[i]);
					if ((l < 0L) || (l > 255L)) {
						return empty;
					}
					bytes[i] = (byte) (int) (l & 0xFF);
				}
				break;
			default:
				return empty;
			}
		}
		catch (NumberFormatException e) {
			return empty;
		}
		return bytes;
	}

	/***
	 * 获取外网IP
	 * @return 结果
	 */
	public static String internetIp() {
		try {

			Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
			InetAddress inetAddress = null;
			Enumeration<InetAddress> inetAddresses = null;
			while (networks.hasMoreElements()) {
				inetAddresses = networks.nextElement().getInetAddresses();
				while (inetAddresses.hasMoreElements()) {
					inetAddress = inetAddresses.nextElement();
					if (inetAddress != null && inetAddress instanceof Inet4Address && !inetAddress.isSiteLocalAddress()
							&& !inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().indexOf(":") == -1) {
						return inetAddress.getHostAddress();
					}
				}
			}

			return null;

		}
		catch (Exception e) {
			throw new SystemErrorException(e);
		}
	}

	/**
	 * 获取内网IP
	 * @return 结果
	 */
	public static String intranetIp() {
		try {
			String realIp = "127.0.0.1";
			Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
			while (allNetInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = allNetInterfaces.nextElement();
				if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
					continue;
				}
				if (!netInterface.getDisplayName().contains("Intel")
						&& !netInterface.getDisplayName().contains("Realtek")) {
					continue;
				}
				Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					InetAddress ip = addresses.nextElement();
					if (ip != null && ip instanceof Inet4Address) {
						realIp = ip.getHostAddress();
						break;
					}
				}
			}
			return realIp;
		}
		catch (Exception e) {
			throw new SystemErrorException(e);
		}
	}

	private static String getLinuxLocalIp() {
		String ip = "";
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				String name = intf.getName();
				if (!name.contains("docker") && !name.contains("lo")) {
					for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
						InetAddress inetAddress = enumIpAddr.nextElement();
						if (!inetAddress.isLoopbackAddress()) {
							String ipaddress = inetAddress.getHostAddress();
							if (!ipaddress.contains("::") && !ipaddress.contains("0:0:")
									&& !ipaddress.contains("fe80")) {
								ip = ipaddress;
							}
						}
					}
				}
			}
		}
		catch (SocketException ex) {
			log.error("获取ip地址异常");
			ip = "127.0.0.1";
			ex.printStackTrace();
		}
		return ip;
	}

	/**
	 * 获取服务启动host
	 * @return 结果
	 */
	public static String getHostIp() {
		if (PlatformUtil.isLinux()) {
			return getLinuxLocalIp();
		}
		else {
			return internetIp() == null ? intranetIp() : internetIp();
		}
	}

	public static String getHostName() {
		try {
			return InetAddress.getLocalHost().getHostName();
		}
		catch (UnknownHostException e) {
			return "未知";
		}

	}

}